package com.quanxiaoha.xiaohashu.user.relation.biz;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
interface DiscountStrategy {
    Double discount(Double price);
    String mark();
}
@Component
class DiscountStrategy1 implements DiscountStrategy{
    @Override
    public Double discount(Double price) {
        return price * 0.95;
    }
    @Override
    public String mark() {
        return "1";
    }
}
@Component
class DiscountStrategy2 implements DiscountStrategy{
    @Override
    public Double discount(Double price) {
        return price * 0.9;
    }
    @Override
    public String mark() {
        return "2";
    }
}
@Component
class DiscountStrategyFactory implements InitializingBean {
    @Autowired
    private ApplicationContext applicationContext;

    private static final Map<String, DiscountStrategy> STRATEGY_MAP = new HashMap<>();

    public  DiscountStrategy chooseStrategy(String type) {
        return STRATEGY_MAP.get(type);
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, DiscountStrategy> beansOfType = applicationContext.getBeansOfType(DiscountStrategy.class);

//        v.mark()为策略对应的key，value为策略对象
        beansOfType.forEach((k, v) -> STRATEGY_MAP.put(v.mark(), v));
    }


}
@Slf4j
@SpringBootTest
class Main {
    @Autowired DiscountStrategyFactory discountStrategyFactory;
    @Test
    void contextLoads() {
        DiscountStrategy discountStrategy = discountStrategyFactory.chooseStrategy("1");
//        System.out.println();
        log.error("Discount Price = {}", discountStrategy.discount(10D));
    }
}


